﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using PServiceBus.Core.Interface;
using PServiceBus.Core.Manager;
using System.Net;

namespace PServiceBus.Core.Runtime.Gateway {
    [Serializable]
    [DataContract]
    public class ServiceInfo : IIdentifiable {
        [DataMember]
        public string ServiceName { get; set; }
        [DataMember]
        public string Endpoint { get; set; }
        [DataMember]
        public int TotalConnectedClients { get; set; }

        private static IObjectManager<ServiceInfo> _services;
        public static IObjectManager<ServiceInfo> Services {
            get { return _services ?? (_services = ObjectManager<ServiceInfo>.Instance); }
        }

        public ServiceInfo() {
            ID = Guid.NewGuid();
        }

        public static ServiceInfo Load(Func<ServiceInfo, bool> predicate) {
            return Services.FirstOrDefault(predicate);
        }

        public void Update() {
            Services.Detach(this);
            Services.Attach(this);
        }

        public void Delete() {
            Services.Detach(this);
        }

        public static ServiceInfo New(string serviceName, int port) {
            var service = Services.FirstOrDefault(s => s.ServiceName == serviceName);
            if (service == null) {
                var ipAddress =
                    Dns.GetHostAddresses(Dns.GetHostName()).First(
                        ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();
                service = new ServiceInfo();
                service.ServiceName = serviceName;
                service.Endpoint = String.Format("endpoint://{0}:{1}", ipAddress, port);
                Services.Attach(service);
            }
            return service;
        }

        #region IIdentifiable Members
        [DataMember]
        public Guid ID { get; set; }

        #endregion
    }
}
